extends layout

block content
  link(rel='stylesheet', href='/stylesheets/video-js.min.css')
  link(rel='stylesheet', href='/stylesheets/style.css')
  .container
    .player-container
      video#my-video.video-js.video-player(
        controls
        preload="auto"
        data-setup='{"fluid": true, "responsive": true, "playbackRates": [0.5, 1, 1.5, 2]}'
      )
        p.vjs-no-js
          | 请启用JavaScript并升级浏览器以
          a(href='http://videojs.com/html5-video-support/' target='_blank') 支持HTML5视频

    .playlist-container
      h3 播放列表
      .playlist#playlist
        .loading 加载中...

  script(src="/javascripts/video.min.js")
  script.
    document.addEventListener('DOMContentLoaded', function() {
      const player = videojs('my-video')
      const playlistEl = document.getElementById('playlist')
      let currentVideo = null
      let isRequesting = false
      
      // 获取播放列表
      fetch('/video/list')
        .then(response => response.json())
        .then(videos => {
          playlistEl.innerHTML = '' // 清空加载状态
          videos.forEach((video, index) => {
            const item = document.createElement('div')
            item.className = 'playlist-item'
            item.innerHTML = `
              <div class="playlist-number">${index + 1}</div>
              <div class="playlist-title">${video.filename}</div>
              <div class="playlist-duration">${formatTime(video.duration_sec)}</div>
            `
            item.addEventListener('click', function(event) {
              playVideo(video)
            
              // 高亮当前播放项
              document.querySelectorAll('.playlist-item').forEach(item => {
                item.classList.remove('active')
              })
              event.currentTarget.classList.add('active')
            })

            playlistEl.appendChild(item)
          })
        })
        .catch(error => {
          playlistEl.innerHTML = '<div class="error">播放列表加载失败</div>'
          console.log('Error:', error)
        })

      // 播放指定视频
      function playVideo(video) {
        isRequesting = true
        fetch('/video/' + video.id)
        .then(response => {
          console.log(response)

            // 根据文件扩展判断MIME类型
            const isHLS = video.url.toLowerCase().endsWith('.m3u8');
            const type = isHLS ? 'application/x-mpegURL' : 'video/mp4'; // 默认类型

            // 切换到新的视频源
            player.src({
                src: video.url,
                type: type
            });

            // 自动播放新视频
            player.load();
            player.play();

            currentVideo = video
        })
        .catch(error => {
          console.log('Error:', error)
        })
        .finally(() => isRequesting = false);
      }
      
      // 格式化视频时长为 HH:MM:SS
      const formatTime = (seconds) => {
        // 将浮点数的秒数转换为整数秒
        seconds = Math.floor(seconds);
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;

        return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
      };

      // 监听音量变化事件
      player.on('volumechange', function() {
        // 保存当前音量到 localStorage
        localStorage.setItem('videojsVolume', player.volume());
      });

      // 页面加载时设置音量
      var savedVolume = localStorage.getItem('videojsVolume');
      if (!savedVolume) {
        savedVolume = 0.5;
      }
      player.volume(parseFloat(savedVolume));
    })